using UnityEngine;
using System.Collections;

public class SnakeBody : MonoBehaviour 
{
	public Transform opposite;
	
	private float force = 50f;
	
	private bool wheel_mode = false;
	private Transform thisTransform;
	private Rigidbody thisRigidbody;
	
	private Vector3 direction;
	private Vector3 tangent;
	
	private float lastPosition;
	private float currentPosition;
	private Transform referencePoint;
	private Color normalColor;
	
	public void Start () 
	{
		thisRigidbody = rigidbody;
		thisTransform = transform;
		tangent = Vector3.zero;
		normalColor = renderer.material.color;
		
		referencePoint = GameObject.Find ("Reference").transform;
	}
	
	public bool WheelMode
	{
		get { return wheel_mode;  }
	}
	
	public void BeginWheelMode ()
	{
		wheel_mode = true;
		lastPosition = currentPosition = referencePoint.position.x;
		renderer.material.SetColor ("_Color", Color.green);
		StartCoroutine ("ForcePush");	
	}
	
	public void StopWheelMode ()
	{	
		wheel_mode = false;
		renderer.material.color = normalColor;
		StopCoroutine ("ForcePush");
	}
	
	public void FixedUpdate ()
	{
		if (wheel_mode)
		{
			Vector3.OrthoNormalize (ref direction, ref tangent);
			Debug.DrawRay (thisTransform.position, tangent, Color.red);
			Debug.Log (gameObject.name + " " + tangent);
			
			float axis = Input.GetAxis ("Horizontal");
			currentPosition = referencePoint.position.x;
			
			//if moving in one direction while wanting to move the opposite direction, increase force to quickly change direction
			if ((axis < 0 && currentPosition > lastPosition) || (axis > 0 &&  currentPosition < lastPosition))
			{
				//Debug.Log ("Moving quickly to break");
				thisRigidbody.AddForce (axis * force * -0.75f * tangent);
			}
			else
			{
				//Debug.Log ("Moving at normal pace.");
				thisRigidbody.AddForce (axis * force / -5 * tangent);
			}
			
			lastPosition = currentPosition;
		}
	}
	
	private IEnumerator ForcePush ()
	{
		while (true)
		{
			direction = (thisTransform.position - opposite.position).normalized;
			
			thisRigidbody.AddForce (direction * force);
			
			yield return null;
		}
	}
}